# 妖股监测
# 监控方法
# （1）已有两个连续涨停板
# （2）监控大单以上进出比
import os
from apscheduler.schedulers.blocking import BlockingScheduler

from utils import date_util, k_util, json_util, doc_util, http_util, chart_util, read_config

today_str = date_util.get_format_date_str("%Y-%m-%d")
base_result_path = os.path.join(read_config.data_path, 'result', '妖股监测', today_str)
result_file_name = '筛选结果'
view_file_path = os.path.join(base_result_path, 'view')

if not os.path.exists(view_file_path):
    os.makedirs(view_file_path)  # 没有创建文件夹

param_n_even_plate = 2  # 配置筛选的连板数


# 筛选妖股
def regulate_demon_stock():
    print('begin regulate stock')
    validation_result = open(os.path.join(base_result_path, result_file_name), mode='w', encoding='utf-8')
    path = os.path.join(read_config.data_path, 'config', '0.股票信息')
    info_list = doc_util.get_path_doc_info(path)
    for info in info_list:
        info = eval(info)
        if (judge_n_continuous_stock(info)):
            print(info)
            # 生成当日的监控日志
            validation_result.write(str(info) + '\n')
            chart_util.day_k_with_path(info['code'], 30, view_file_path)
    validation_result.flush()
    validation_result.close()


def judge_n_continuous_stock(info):
    # 增加偏移量 todo 收盘后偏移量为0
    for num in range(param_n_even_plate):
        day_k_result = k_util.day_k_local(info['code'], param_n_even_plate + 2)
        one_sp = float(json_util.info_to_json(day_k_result[num + 1])['sp'])
        two_sp = float(json_util.info_to_json(day_k_result[num + 2])['sp'])
        if (k_util.judge_harden(one_sp, two_sp) == 0): return 0
        thr_sp = float(json_util.info_to_json(day_k_result[num + 3])['sp'])
        if (k_util.judge_harden(two_sp, thr_sp) == 0): return 0
        return 1


def init_data():
    update_flag = input('输入是否重新筛选股票(1更新,回车下一步)********:')
    if update_flag != '' or update_flag == 1:
        regulate_demon_stock()


def demon_stock_monitor():
    info_list = doc_util.get_path_doc_info(os.path.join(base_result_path, result_file_name))
    for stock_info in info_list:
        stock_info = json_util.info_to_json(stock_info)
        print(stock_info)
        stock_list = http_util.rt_dynamic(stock_info['code'])
        print(stock_list)


def begin_job():
    init_data()
    scheduler = BlockingScheduler()
    # 添加任务,时间间隔 100S
    scheduler.add_job(demon_stock_monitor(), 'interval', seconds=10, id='demon_stock_monitor')
    scheduler.start()


if __name__ == '__main__':
    print('********监控妖股 start*******')
    begin_job()
    print('********监控妖股 end*******')
